package cn.wilson.hrm.service;

import cn.wilson.hrm.doc.CourseDoc;
import cn.wilson.hrm.query.CourseQuery;
import cn.wilson.hrm.repository.CourseElasticsearchRepository;
import cn.wilson.hrm.utils.PageList;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class EsService {

    @Autowired
    private CourseElasticsearchRepository courseElasticsearchRepository;


    public PageList<CourseDoc> searchCourse(CourseQuery courseQuery) {

        //要把CourseQuery封装成builder对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();


        //查询条件===
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //DSL查询 must是必须匹配
        List<QueryBuilder> must = boolQueryBuilder.must();
        //        keyword: ""
        if (StringUtils.hasLength(courseQuery.getKeyword())){
            //如果你输入了关键字查询，我才查询   关键字使用match
            must.add(QueryBuilders.matchQuery("name",courseQuery.getKeyword()));
        }
        //DSL过滤
        List<QueryBuilder> filter = boolQueryBuilder.filter();
        //        priceMax: null
        if (courseQuery.getProductType() != null){
            //如果没有点击分类，就不查询
            filter.add(QueryBuilders.termQuery("courseTypeId",courseQuery.getProductType()));
        }
        //        priceMin: null       如果你传了我再查
        if (courseQuery.getPriceMin() != null){
            //大于等于最小价格
            filter.add(QueryBuilders.rangeQuery("price").gte(courseQuery.getPriceMin()));
        }
        //        productType: "1040"   你不为空我再查
        if (courseQuery.getPriceMax() != null){
            //小于等于最大价格
            filter.add(QueryBuilders.rangeQuery("price").lte(courseQuery.getPriceMax()));
        }

        //关联查询条件
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);


        //排序
        //排序的默认通过什么来排序
        String sortFieldName = "price";
        //前台传递编号 我们需要把这儿编号转一下
        if (StringUtils.hasLength(courseQuery.getSortField())){
            //只有你前台传了关键字来排序，我才排序
            switch (courseQuery.getSortField().toUpperCase()){
                case "XL": sortFieldName = "buyCount";break;
                case "XP": sortFieldName = "onlineTime";break;
                case "PL": sortFieldName = "commentCount";break;
                case "JG": sortFieldName = "price";break;
                case "RQ": sortFieldName = "viewCount";break;
            }
            //默认排序方式
            SortOrder sortOrder = SortOrder.DESC;
            //如果前台传了排序方式，升序，修改为升序
            if (StringUtils.hasLength(courseQuery.getSortType()) && courseQuery.getSortType().toUpperCase().equals("ASC")){
                sortOrder = SortOrder.ASC;
            }
            //添加排序条件
            nativeSearchQueryBuilder.withSort(new FieldSortBuilder(sortFieldName).order(sortOrder));
        }
        //分页    传入当前页和每页条数,我们的是从1开始的，而of方法里面的page查询条件是从0开始
        nativeSearchQueryBuilder.withPageable(PageRequest.of(courseQuery.getPage()-1,courseQuery.getRows()));

        //执行查询 处理结果
        SearchQuery searchQuery = nativeSearchQueryBuilder.build();
        Page<CourseDoc> page = courseElasticsearchRepository.search(searchQuery);
        //把es的page对象转成pagelist对象返回
        return new PageList<CourseDoc>(page.getTotalElements(),page.getContent());
    }
}
